package com.yjc.hire.handles;

import com.yjc.hire.exceptions.MyCustomException;
import com.yjc.hire.grace.result.GraceJSONResult;
import com.yjc.hire.grace.result.ResponseStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *
 * @author jcyin
 * @since 2025/7/3
 * </p>
 */

/**
 * 异常拦截器
 */
@ControllerAdvice(annotations = {RestController.class})
@Slf4j
public class GraceExceptionHandle {

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public GraceJSONResult handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        return GraceJSONResult.exception(ResponseStatusEnum.FILE_MAX_SIZE_500KB_ERROR);
    }


    @ExceptionHandler(MyCustomException.class)
    @ResponseBody
    public GraceJSONResult returnMyCustomException(MyCustomException e) {

        log.info("得到的异常为" + e.getResponseStatusEnum());

        return GraceJSONResult.exception(e.getResponseStatusEnum());

    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public GraceJSONResult returnMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("得到的的异常信息为" + e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        BindingResult result = e.getBindingResult();
        Map<String, String> errorMaps = getErrors(result);
        return GraceJSONResult.errorMap(errorMaps);
    }

    public Map<String,String> getErrors(BindingResult result){

        Map<String,String> map = new HashMap<>();

        List<FieldError> errors = result.getFieldErrors();
        for (FieldError error : errors) {
            String message = error.getDefaultMessage();
            String field = error.getField();
            map.put(field, message);
        }
        return map;
    }
}
